package com.tiancheng.trade.payment.service.impl;

import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.commom.core.exception.Asserts;
import com.tiancheng.trade.commom.web.cache.MerchantCache;
import com.tiancheng.trade.commom.web.feign.MerchantFeignService;
import com.tiancheng.trade.commom.web.model.request.MerchantChannelRequestDTO;
import com.tiancheng.trade.commom.web.model.response.MerchantChannelResponseDTO;
import com.tiancheng.trade.payment.service.PaymentMerchantPlatformService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 支付相关商户service
 *
 * @Date 2025/02/24
 * @Author DCH
 */
@Service
@Slf4j
public class PaymentMerchantPlatformServiceImpl implements PaymentMerchantPlatformService {

    @Resource
    private MerchantFeignService merchantFeignService;

    @Override
    public List<MerchantChannelResponseDTO> queryByMerchantCodeAndChannel(List<MerchantChannelRequestDTO> list) {
        // 从缓存取一次
        List<MerchantChannelResponseDTO> result=new ArrayList<>(list.size());
        List<MerchantChannelRequestDTO> queryMerchants=new ArrayList<>();
        for (MerchantChannelRequestDTO item : list) {
            Optional<MerchantChannelResponseDTO> cachePaymentSubMerchant = MerchantCache.getCachePaymentSubMerchant(item.getOrgPaymentChannelId(), item.getMerchantCode());
            if(cachePaymentSubMerchant.isPresent()){
                result.add(cachePaymentSubMerchant.get());
                continue;
            }
            queryMerchants.add(item);
        }
        // 没有则调用支付中心取
        if(CollectionUtils.isNotEmpty(queryMerchants)){
            Result<List<MerchantChannelResponseDTO>> listResult = merchantFeignService.listByMerchantCodeAndChannel(queryMerchants);
            Asserts.isTrue(listResult.getRet()==0,"查询支付商户信息失败！");
            for (MerchantChannelResponseDTO item : listResult.getData()) {
                result.add(item);
                MerchantCache.cachePaymentSubMerchant(item);
            }
        }
        return result;
    }
}
